# coding=utf-8
from flask import g
from flask import request
from flask import session, jsonify

from info.models import User, News, Category
from info.utils.commom import user_login_data
from info.utils.response_code import RET
from . import index_blue
from flask import render_template,current_app


#处理404页面的
@index_blue.route('/404')
@user_login_data
def page_not_found():
    if not g.user:
        return jsonify(errno=RET.DATAERR,errmsg="用户未登录")
    data = {
        "user_info":g.user.to_dict(),
    }

    return render_template('news/404.html',data=data)


@index_blue.route('/newslist')
def newslist():
    # 1 数据获取,"page": cur_page,"cid": currentCid,'per_page': 5
    page = request.args.get("page","1")
    cid = request.args.get("cid","1")
    per_page = request.args.get("per_page","5")

    # 2 转换数据
    try:
        page = int(page)
        # cid = int(cid)
        per_page = int(per_page)
    except:
        # current_app.logger.error(e)
        page = 1
        # cid = 1
        per_page = 5

    # condition = ""
    condition = [News.status == 0]
    if cid != "1":
        # condition = (News.category_id == cid)
        condition.append(News.category_id == cid)
    # paginate = News.query.filter(condition).order_by(News.create_time.desc()).paginate(page,per_page,False)
    paginate = News.query.filter(*condition).order_by(News.create_time.desc()).paginate(page, per_page,False)

    totalPage = paginate.pages
    items = paginate.items
    per_page = paginate.per_page

    # 3 转换成字典列表
    newsList = []
    for news in items:
        newsList.append(news.to_dict())

    # 3 分页查询数据,组织数据
    return jsonify(errno=RET.OK,errmsg="获取新闻列表成功",newsList=newsList, totalPage=totalPage, per_page=per_page)


@index_blue.route('/favicon.ico')
def get_logo():
    response = current_app.send_static_file("news/favicon.ico")
    return response


@index_blue.route('/',methods=["GET","POST"])
def show_index():
    # 右上角用户名称显示
    # 1 数据获取
    user_id = session.get("user_id")
    # 2 根据用户编号获取对用户对象
    user = None
    if user_id:
        user = User.query.filter(User.id == user_id).first()
        # user = User.query.get(user_id)

    # 热门新闻排行
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
        # news_list = News.query.order_by(News.clicks.desc()).limit(10)
    except Exception as e:
        current_app.logger.error(e)

    clicks_news_list = []
    for news in news_list:
        clicks_news_list.append(news.to_dict())

    # 查询所有的分类,转成字典列表
    try:
        categories = Category.query.all()
        # categories = Category.query.get() # 不正确
    except Exception as e:
        current_app.logger.error(e)

    category_list = []

    for category in categories:
        category_list.append(category.to_dict())

    data ={
        "clicks_news_list":clicks_news_list,
        "category_list":category_list,
        "user_info": user.to_dict() if user else "",
    }

    return render_template("news/index.html", data=data)